package task.manager.view;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import task.manager.R;
import task.manager.model.Task;
import task.manager.model.TaskApplication;

import android.graphics.drawable.Drawable;
import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.location.Address;
import android.location.Geocoder;

// TODO: Auto-generated Javadoc
/**
 * The Class AndroidGoogleMapsProjectActivity.
 */
public class AndroidGoogleMapsProjectActivity extends MapActivity {

	/** The map view. */
	private MapView mapView;
	
	/** The geocoder. */
	private Geocoder geocoder;
	
	/** The facade. */
	final TaskApplication facade = TaskApplication.getInstance();

	/* (non-Javadoc)
	 * @see com.google.android.maps.MapActivity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);

		mapView = (MapView) findViewById(R.id.map_view);
		mapView.setBuiltInZoomControls(true);

		MapController mapController = mapView.getController();
		Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);

		LinkedList<Task> tasks = facade.getTaskList();
		Iterator<Task> it = tasks.iterator();
		while (it.hasNext()) {
			Task curr = it.next();
			Address location = null;
			try {
				List<Address> address = geocoder.getFromLocationName(
						curr.getLocation(), 1);

				if (!address.isEmpty()) {
					location = address.get(0);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}

			if (location != null) {
				List<Overlay> mapOverlays = mapView.getOverlays();
				Drawable drawable = this.getResources().getDrawable(
						R.drawable.heart);
				CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(
						drawable, this);

				GeoPoint point = new GeoPoint(
						(int) (location.getLatitude() * 1E6),
						(int) (location.getLongitude() * 1E6));
				OverlayItem overlayitem = new OverlayItem(point, curr.getTaskName(),
						curr.getDescription());

				itemizedOverlay.addOverlay(overlayitem);
				mapOverlays.add(itemizedOverlay);

				mapController.animateTo(point);
			}
		}
		mapController.setZoom(10);

	}

	/* (non-Javadoc)
	 * @see com.google.android.maps.MapActivity#isRouteDisplayed()
	 */
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

}